﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace Baula.TextGen.ActiveTemplating
{
    public class ReadAheadEnumerator<T> : IEnumerator<T>
        where T : class
    {
        private readonly IEnumerator<T> _enumerator;
        private T _currentItem;
        private T _nextItem;
        private bool _moved;

        public ReadAheadEnumerator(IEnumerable<T> items)
        {
            _enumerator = items.GetEnumerator();
        }

        public bool MoveNext()
        {
            var canMove = _enumerator.MoveNext();
            if (!_moved)
            {
                _currentItem = _enumerator.Current;
                _enumerator.MoveNext();
            }
            else
            {
                _currentItem = _nextItem;
            }
            _nextItem = _enumerator.Current;
            _moved = true;
            return canMove;
        }

        public void Reset()
        {
            _enumerator.Reset();
            _moved = false;
            _currentItem = null;
            _nextItem = null;
        }

        public T Current
        {
            get { return _currentItem; }
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }

        public T NextItem
        {
            get
            {
                if (!_moved)
                    throw new Exception("Enumeration not started. Call MoveNext() upfront.");
                return _nextItem;
            }
        }

        public void Dispose()
        {
            _enumerator.Dispose();
        }
    }
}